package meituan.food;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ifast.demo.domain.MeitTuanLicenseFoodDO;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.model.HttpRequestBody;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.utils.HttpConstant;

/**
 * @author code4crafter@gmail.com <br>
 */
public class MeituanFoodLicenseProcessor implements PageProcessor {
   
	public static String key = "zzDbKey";
	
	@Override
    public void process(Page page) { 
		if(page.getJson() != null) {
			  JSONObject obj = JSON.parseObject(page.getJson().toString());
	    	  System.out.println(obj.getString("data"));
	    	  MeitTuanLicenseFoodDO lices=JSON.parseObject(obj.getString("data"),MeitTuanLicenseFoodDO.class); 
	    	  lices.setPoiId(Integer.valueOf(page.getRequest().getExtra("poiId").toString()));
	    	  page.putField(key, lices);
	    	  System.out.println(lices);
		} 
    }

    @Override
    public Site getSite() {
    	Site site = Site.me().setDomain("chifeng.meituan.com");
    	site.addHeader("Content-Type","application/json");
    	site.addHeader("Origin","https://chifeng.meituan.com");
    	site.addHeader("Referer","https://chifeng.meituan.com/meishi/164844118/"); 
    	site.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
    	site.addHeader("Sec-Fetch-Mode","cors");
        return site;
    }

    public static void main(String[] args){ 
		Request loing = new Request("https://chifeng.meituan.com/meishi/api/poi/getFoodSafetyDetail");  
		loing.putExtra("poiId", "164844118");
    	loing.setMethod(HttpConstant.Method.POST).setRequestBody(HttpRequestBody.json("{\"poiId\":\"164844118\"}", "UTF-8"));
        Spider.create(new MeituanFoodLicenseProcessor()).addRequest(loing).run();
    }

}
